package com.bwie.es.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.Ticket;
import com.bwie.common.domain.dto.TicketDTO;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.StringUtils;
import com.bwie.es.service.ESService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class ESServiceImp implements ESService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public PageResult<Ticket> list(TicketDTO ticketDTO) {
        //定义总记录数
        long total=0;
        //当前页数据
        ArrayList<Ticket> list = new ArrayList<>();
        try{
            SearchRequest searchRequest = new SearchRequest("ticket");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            if(!StringUtils.isEmpty(ticketDTO.getTicketDeparture())){
                boolQueryBuilder.must(QueryBuilders.matchQuery("ticketDeparture",ticketDTO.getTicketDeparture()));
            }
            if(StringUtils.isNotBlank(ticketDTO.getAirlineCompany())){
                boolQueryBuilder.must(QueryBuilders.matchQuery("airlineCompany",ticketDTO.getAirlineCompany()));
            }

            if(null!=ticketDTO.getStartDate()){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("startDate").gte(ticketDTO.getStartDate().getTime()));
            }
            if(null!=ticketDTO.getEndDate()){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("endDate").lte(ticketDTO.getEndDate().getTime()));
            }

            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.from((ticketDTO.getPageNum()-1)*ticketDTO.getPageSize());
            searchSourceBuilder.size(ticketDTO.getPageSize());
            //<span style="color:red;">
            searchSourceBuilder.highlighter(new HighlightBuilder().field("ticketDeparture").preTags("<span style=\"color:red;\">").postTags("</span>"));
            searchSourceBuilder.sort("startDate", SortOrder.DESC);

            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            total = searchHits.getTotalHits().value;
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                Ticket ticket = JSONObject.parseObject(sourceAsString, Ticket.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(null!=highlightFields && highlightFields.size()>0){
                    HighlightField highlightField = highlightFields.get("ticketDeparture");
                    if(null!=highlightField){
                        Text[] fragments = highlightField.fragments();

                        StringBuilder sb = new StringBuilder();
                        for (Text fragment : fragments) {
                            sb.append(fragment);
                        }
                        ticket.setTicketDestination(sb.toString());
                    }
                }
                ticket.setAirlineCompany(hit.getId());
                list.add(ticket);
            }
        } catch (IOException e) {
           log.error("搜索文章异常:{},异常内容:{}",e.getMessage(),JSONObject.parseObject(String.valueOf(ticketDTO)));
        }
        return PageResult.toPageResult(total,list);
    }

    @Override
    public void bulk(List<Ticket> tickets) {
        try{
            BulkRequest bulkRequest = new BulkRequest("ticket");
            tickets.forEach(ticketsaa->{
                bulkRequest.add(
                        new IndexRequest("ticket")
                                .id(ticketsaa.getTicketId()+"")
                                .source(JSONObject.toJSONString(ticketsaa), XContentType.JSON));
            });
            restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);

        } catch (IOException e) {

        }
    }
}
